<template>
  <view class="home-container">
    <!-- 批量删除按钮区域 - 统一样式但保留平台特定尺寸 -->
    <!-- #ifdef H5 -->
    <view class="action-bar">
      <u-button type="error" @click="handleBatchDelete">
        批量删除
      </u-button>
    </view>
    <!-- #endif -->
    
    <!-- #ifdef MP-WEIXIN -->
    <view class="action-bar">
      <u-button type="error" @click="handleBatchDelete" size="mini">
        批量删除
      </u-button>
    </view>
    <!-- #endif -->
    
    <view class="welcome-title">
      欢迎回来，<text class="username">sgner</text>
    </view>
    <view class="subtitle">今天我们要使用哪个知识库?</view>
    
    <!-- 知识库列表 -->
    <view class="knowledge-list">
      <checkbox-group @change="onCheckboxGroupChange">
        <view 
          v-for="item in datasetList" 
          :key="item.id" 
          class="knowledge-item"
        >
          <checkbox
            :value="item.id"
            :checked="selectedIds.includes(item.id)"
            style="margin-right: 12px; width: 20px; height: 20px;"
            @tap.stop
          />
          
          <!-- 自定义卡片，使用 view 替代 u-card -->
          <view class="custom-card" @tap="handleCardClick(item)">
            <view class="card-header">
              <u-avatar size="60" :src="item.avatar" />
              <view class="card-title">{{item.name}}</view>
              <view class="card-more" @tap.stop="changeKnowledge">
                <u-icon name="more" size="24" color="#bbb" />
              </view>
            </view>
            <view class="card-content">
              <view class="knowledge-title">{{item.description}}</view>
              <view class="knowledge-info">
                <view class="icon-border">
                  <u-icon name="file-text" size="18" color="#888" />
                </view>
                <text>{{ item.documentCount || 0 }} 文档</text>
              </view>
              <view class="knowledge-date">
                <view class="icon-border">
                  <u-icon name="calendar" size="18" color="#888" />
                </view>
                <text>{{ currentTime }}</text>
              </view>
              <view class="card-footer">
                <view class="card-footer-item">
                  <u-button type="primary" size="mini" @tap.stop="handleUpdate(item.id)">修改</u-button>
                </view>
              </view>
            </view>
          </view>
        </view>
      </checkbox-group>
    </view>
    
    <!-- 创建知识库弹出框 -->
    <view v-if="showPopup" class="custom-popup-mask" @tap.stop="showPopup = false">
      <view class="custom-popup-content" @tap.stop>
        <view class="popup-title">创建知识库</view>
        <UInput v-model="form.name" placeholder="知识库名称" />
        <UInput v-model="form.avatar" placeholder="头像URL" />
        <UTextarea v-model="form.description" placeholder="描述" />
        <UInput v-model="form.language" placeholder="语言" />
        <UInput v-model="form.embedding_model" placeholder="Embedding Model" />
        <UInput v-model="form.permission" placeholder="权限" />
        <UInput v-model="form.chunk_method" placeholder="分块方式" />
        <UTextarea v-model="form.parser_config" placeholder="解析配置" />
        <view class="popup-actions">
          <UButton type="primary" @tap="submitForm">创建</UButton>
          <UButton @tap="showPopup = false" type="default">取消</UButton>
        </view>
      </view>
    </view>
    
    <!-- 编辑知识库弹出框 -->
    <view v-if="showEditPopup" class="custom-popup-mask" @tap.stop="showEditPopup = false">
      <view class="custom-popup-content" @tap.stop>
        <view class="popup-title">编辑知识库</view>
        <UInput v-model="editForm.name" placeholder="知识库名称" />
        <UInput v-model="editForm.embedding_model" placeholder="Embedding Model" />
        <UInput v-model="editForm.chunk_method" placeholder="分块方式" />
        <view class="popup-actions">
          <UButton type="primary" @tap="submitEditForm">保存</UButton>
          <UButton @tap="showEditPopup = false" type="default">取消</UButton>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { getCurrentTime } from '@/utils/time.js'
import { ref, onMounted, onUnmounted } from 'vue'
import uAvatar from 'uview-plus/components/u-avatar/u-avatar.vue'
import uIcon from 'uview-plus/components/u-icon/u-icon.vue'
import UPopup from 'uview-plus/components/u-popup/u-popup.vue'
import UInput from 'uview-plus/components/u--input/u--input.vue'
import UTextarea from 'uview-plus/components/u-textarea/u-textarea.vue'
import UButton from 'uview-plus/components/u-button/u-button.vue'
import { createDataset } from '@/commoms/dataset/createDataset'
import { listDatasets } from '@/commoms/dataset/listDatasets'
import { deleteDataset } from '@/commoms/dataset/deleteDataset'
import { updateDataset } from '@/commoms/dataset/updataDataset'
import { listDocument } from '@/commoms/document/listDocument'
const showPopup = ref(false)
const form = ref({
  name: '',
  avatar: '',
  description: '',
  language: '',
  embedding_model: '',
  permission: '',
  chunk_method: '',
  parser_config: ''
})
const currentTime = ref('')
const datasetList = ref([])
const selectedIds = ref([])
let timer = null
const showEditPopup = ref(false)
const editForm = ref({
  id: '',
  name: '',
  embedding_model: '',
  chunk_method: ''
})

onMounted(async () => {
  currentTime.value = getCurrentTime()
  timer = setInterval(() => {
    currentTime.value = getCurrentTime()
  }, 1000)
  console.log('onMounted')
  
  // 平台检测
  let platform = '';
  // #ifdef MP-WEIXIN
  platform = 'mp-weixin';
  console.log('当前运行在微信小程序环境');
  // #endif
  
  // #ifdef H5
  platform = 'h5';
  console.log('当前运行在H5环境');
  // #endif
  
  console.log('检测到平台:', platform);
  console.log(showPopup.value);
  
  const params = {
    page: 1,
    page_size: 10
  }
  console.log(params)
  const res = await getDatasetList(params)
  datasetList.value = res.data.data
  console.log(selectedIds.value.length)
  console.log('打印日志1')
  console.log(datasetList.value)
  console.log('打印日志2')
  
  // 获取每个知识库的文档列表
  if (datasetList.value && datasetList.value.length > 0) {
    try {
      for (const dataset of datasetList.value) {
        console.log(`获取知识库 ${dataset.name} (ID: ${dataset.id}) 的文档列表`)
        const docParams = {
          page_size: 5,
          page: 1,
          orderby: "string",
          desc: true,
          keywords: "string",
          name: dataset.name
        }
        const docRes = await listDocument(dataset.id, docParams)
        console.log(`知识库 ${dataset.name} 的文档列表:`, docRes)
        // 将文档数量保存到知识库对象中
        dataset.documentCount = docRes.data ? docRes.data.length : 0
      }
    } catch (error) {
      console.error('获取文档列表出错:', error)
    }
  }
})

onUnmounted(() => {
  if (timer) clearInterval(timer)
})

function handleCardClick(item) {
  console.log('点击卡片，准备跳转:', item);
  console.log('知识库名称:', item.name);
  console.log('知识库ID:', item.id);
  
  // 显示点击反馈
  uni.showToast({
    title: '卡片点击',
    icon: 'none',
    duration: 500
  });
  
  try {
    setTimeout(() => {
      // 构建跳转参数，使用更明确的参数名称
      const url = `/pages/dialog/dialog?kbName=${encodeURIComponent(item.name || '')}
      &knowledge=${encodeURIComponent(item.description || '')}
      &avatar=${encodeURIComponent(item.avatar || '')}&kbId=${encodeURIComponent(item.id || '')}`;
      console.log('完整跳转URL:', url);
      
      // 使用uni.navigateTo统一处理跳转
      uni.navigateTo({
        url: url,
        success(res) {
          console.log('跳转成功', res);
        },
        fail(err) {
          console.error('跳转失败:', err);
          uni.showToast({
            title: '跳转失败',
            icon: 'none'
          });
        }
      });
    }, 100);
  } catch (error) {
    console.error('跳转出错:', error);
  }
}

async function submitForm() {
  // 这里可以提交form.value到后端或做其它处理
  uni.showToast({ title: '创建成功', icon: 'success' })
  showPopup.value = false
  const res = await createDataset(form.value)
  console.log(res)
  const resList = await getDatasetList({page: 1, page_size: 10})
  datasetList.value = resList.data.data
}

function changeKnowledge() {
  showPopup.value = !showPopup.value
  console.log('changeKnowledge')
  console.log(showPopup.value)
}

async function getDatasetList(params) {
  try {
    console.log('获取知识库列表，参数:', params)
    const res = await listDatasets(params)
    console.log('获取知识库列表结果:', res)
    
    // 处理模拟数据的情况
    if (res.message && res.message.includes('mock')) {
      console.log('使用模拟数据')
      return {
        data: {
          data: res.data.data,
          total: res.data.total
        }
      }
    }
    
    return res
  } catch (error) {
    console.error('获取知识库列表出错:', error)
    uni.showToast({
      title: '获取知识库列表失败',
      icon: 'none'
    })
    // 返回空数据，防止界面崩溃
    return {
      data: {
        data: [],
        total: 0
      }
    }
  }
}

function onCheckboxGroupChange(e) {
  selectedIds.value = e.detail.value
}

async function handleBatchDelete() {
  console.log(selectedIds.value)
  console.log('批量删除')
  if (selectedIds.value.length === 0) {
    console.log('日志1')
    uni.showToast({ title: '请选择要删除的知识库', icon: 'none' })
    console.log('日志2')
    return
  }
  console.log('传递的ids')
  console.log(selectedIds.value)
  console.log('传递的ids')
  await deleteDataset({ ids: selectedIds.value })
  // 删除成功后刷新列表
  const params = { page: 1, page_size: 10 }
  const resList = await getDatasetList(params)
  datasetList.value = resList.data.data
  selectedIds.value = []
}

async function handleUpdate(id) {
  const item = datasetList.value.find(d => d.id === id)
  if (item) {
    editForm.value = {
      id: item.id,
      name: item.name,
      embedding_model: item.embedding_model,
      chunk_method: item.chunk_method
    }
    showEditPopup.value = true
  }
}

async function submitEditForm() {
  const res = await updateDataset({
    id: editForm.value.id,
    name: editForm.value.name,
    embedding_model: editForm.value.embedding_model,
    chunk_method: editForm.value.chunk_method
  })
  console.log(res)
  uni.showToast({ title: '修改成功', icon: 'success' })
  showEditPopup.value = false
  // 刷新列表
  const params = { page: 1, page_size: 10 }
  const resList = await getDatasetList(params)
  datasetList.value = resList.data.data
}
</script>

<style scoped>
/* 根容器样式 */
.home-container {
  padding: 16px;
  box-sizing: border-box;
}

/* 批量删除按钮区域 */
.action-bar {
  margin-bottom: 16px;
  text-align: right;
}

/* 标题样式 */
.welcome-title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 12px;
  text-align: center;
}

.username {
  color: #409EFF;
}

.subtitle {
  color: #666;
  margin-bottom: 20px;
  text-align: center;
  font-size: 16px;
}

/* 列表布局 */
.knowledge-list {
  display: flex;
  flex-direction: column;
  width: 100%;
}

/* 知识库项目容器 */
.knowledge-item {
  display: flex;
  align-items: flex-start;
  width: 100%;
  margin-bottom: 15px;
}

/* 自定义卡片样式 */
.custom-card {
  flex: 1;
  padding: 16px;
  border-radius: 12px;
  background: #fff;
  border: 1px solid #e5e6eb;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
  position: relative;
}

/* 卡片头部 */
.card-header {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  width: 100%;
}

.card-title {
  margin-left: 16px;
  font-size: 18px;
  font-weight: bold;
  flex: 1;
}

.card-more {
  margin-left: auto;
}

/* 卡片内容 */
.card-content {
  width: 100%;
}

/* 知识库内容 */
.knowledge-title {
  font-size: 16px;
  margin-bottom: 14px;
  word-break: break-all;
}

.knowledge-info, .knowledge-date {
  display: flex;
  align-items: center;
  color: #888;
  font-size: 14px;
  margin-bottom: 8px;
}

.icon-border {
  width: 28px;
  height: 28px;
  border: 1px solid #e5e6eb;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 8px;
  background: #fff;
}

/* 卡片底部 */
.card-footer {
  display: flex;
  justify-content: flex-end;
  width: 100%;
  margin-top: 12px;
}

.card-footer-item {
  margin-left: 8px;
}

/* 弹窗样式 - 统一H5和小程序的样式 */
.custom-popup-mask {
  position: fixed;
  z-index: 9999;
  left: 0; top: 0; right: 0; bottom: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  align-items: center;
  justify-content: center;
}

.custom-popup-content {
  background: #fff;
  border-radius: 12px;
  padding: 20px;
  width: 80%;
  max-height: 70vh;
  box-shadow: 0 4px 16px rgba(0,0,0,0.1);
  display: flex;
  flex-direction: column;
  gap: 10px;
  overflow-y: auto;
}

.popup-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 8px;
  text-align: center;
}

.popup-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 16px;
  gap: 12px;
}
</style>
